import requests
from bs4 import BeautifulSoup

strurl = 'http://books.toscrape.com'
nexturl = strurl

# print(res.text)

while nexturl:
    #获取页面元素
    res = requests.get(nexturl)
    bs = BeautifulSoup(res.text, 'lxml')
    # print(bs.find_all('div',class_='image_container'))
    for div in bs.find_all('div',class_='image_container'):
        #判断页面前缀是否包含 catalogue ，如果不包含，则补充进url
        if 'catalogue' in div.a['href']:
            bookurl = strurl + '/' + div.a['href']
        else:
            bookurl = strurl + '/catalogue/' + div.a['href']
        # 获取图书子页面内容，下述为各个图书的描述信息
        res2 = requests.get(bookurl)
        bs2 = BeautifulSoup(res2.text, 'lxml')
        book_name = bs2.find('div',class_='col-sm-6 product_main').find_all('h1')[0].text
        print('图书名称：' + book_name)
        book_type = bs2.find('ul',class_='breadcrumb').find_all('li')[2].text
        print('图书类型：' + book_type.replace('\n', ''))
        book_price = bs2.find('div',class_='col-sm-6 product_main').find_all('p')[0].text
        print('图书价格：' + book_price)
        book_insock = bs2.find('table',class_='table table-striped').find_all('tr')[5].td.text
        print('图书库存：' + book_insock)
        book_img = strurl + bs2.find('div',class_='item active').img['src'][5:]
        print('图书图片：' + book_img)
        book_src = bs2.find('article',class_='product_page').find_all('p')[3].text
        print('图书描述：' + book_src)
        print()
    #判断是否到底，到了则跳出循环
    if not bs.find('li', class_='next'):
        break
    #判断前缀是否包含，不包含则添加进去
    if 'catalogue' in bs.find('li', class_='next').a['href']:
        nexturl = strurl + '/' + bs.find('li', class_='next').a['href']
    else:
        nexturl = strurl + '/catalogue/' + bs.find('li', class_='next').a['href']
    # print(nexturl)